package com.adong.juc;

import org.omg.CORBA.TIMEOUT;

import java.util.concurrent.*;

/**
 * 阻塞队列
 */
public class BlockingQueueDemo {
    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);


        // 第一组
        System.out.println(blockingQueue.add("a")); // true
        System.out.println(blockingQueue.add("b")); // true
        System.out.println(blockingQueue.add("c")); // true
        System.out.println(blockingQueue.element()); // a
        //System.out.println(blockingQueue.add("d")); java.lang.IllegalStateException: Queue full
        System.out.println(blockingQueue.remove()); // a
        System.out.println(blockingQueue.remove()); // b
        System.out.println(blockingQueue.remove()); // c
        //System.out.println(blockingQueue.element()); java.util.NoSuchElementException

        // 第二组
        System.out.println(blockingQueue.offer("a")); // true
        System.out.println(blockingQueue.offer("b")); // true
        System.out.println(blockingQueue.offer("c")); // true
        System.out.println(blockingQueue.offer("d")); // false
        System.out.println(blockingQueue.poll()); // a
        System.out.println(blockingQueue.poll()); // b
        System.out.println(blockingQueue.poll()); // c
        System.out.println(blockingQueue.poll()); // null

        // 第三组
        blockingQueue.put("a");
        blockingQueue.put("b");
        blockingQueue.put("c");
        //blockingQueue.put("d"); // 阻塞,等待有人获取才能获取存入

        System.out.println(blockingQueue.take()); // a
        System.out.println(blockingQueue.take()); // b
        System.out.println(blockingQueue.take()); // c
        //System.out.println(blockingQueue.take()); // 阻塞,等待有人存值才能获取输出

        // 第四组
        System.out.println(blockingQueue.offer("a")); // true
        System.out.println(blockingQueue.offer("b")); // true
        System.out.println(blockingQueue.offer("c")); // true
        //System.out.println(blockingQueue.offer("d", 4, TimeUnit.SECONDS));// 4m 没有空位存值就返回false,线程退出

        System.out.println(blockingQueue.poll()); // a
        System.out.println(blockingQueue.poll()); // b
        System.out.println(blockingQueue.poll()); // c
        System.out.println(blockingQueue.poll(4, TimeUnit.SECONDS)); // 4m 取不到值返回false,线程退出
    }
}
